<?php

namespace app\common\model;

use think\Model;
use fast\Random;

class Merchant extends Model
{
    // 设置表名
    protected $name = 'merchant';
    // 设置主键
    protected $pk = 'id';
    // 自动时间戳
    protected $autoWriteTimestamp = true;
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 密码加密
    public function setPasswordAttr($value)
    {
        return password_hash($value, PASSWORD_DEFAULT);
    }

    // 生成商家业务ID
    public function generateMerchantId()
    {
        $prefix = 'MER' . date('Ymd');
        $count = $this->where('merchant_id', 'like', $prefix . '%')->count();
        $sequence = str_pad($count + 1, 4, '0', STR_PAD_LEFT);
        return $prefix . $sequence;
    }

    // 验证手机号是否已注册
    public function checkPhoneExist($phone)
    {
        return $this->where('phone', $phone)->count() > 0;
    }

    // 验证登录
    public function login($phone, $password)
    {
        $merchant = $this->where('phone', $phone)->find();
        if (!$merchant) {
            return ['code' => -1, 'msg' => '账号不存在'];
        }

        if (md5($password) != $merchant['password']) {
            return ['code' => -3, 'msg' => '密码错误'];
        }
        return ['code' => 1, 'data' => $merchant];
    }

    // 追加属性
    protected $append = [
        'status_text',
        'verification_status_text'
    ];

    /**
     * 获取状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $status = $data['status'] ?? 0;
        $statusArray = [0 => '禁用', 1 => '正常'];
        return isset($statusArray[$status]) ? $statusArray[$status] : '未知';
    }

    /**
     * 获取认证状态文本
     */
    public function getVerificationStatusTextAttr($value, $data)
    {
        $status = $data['verification_status'] ?? 0;
        $statusArray = [0 => '未认证', 1 => '已认证', 2 => '认证失败'];
        return isset($statusArray[$status]) ? $statusArray[$status] : '未知';
    }

    /**
     * 获取状态列表
     */
    public function getStatusList()
    {
        return [0 => '禁用', 1 => '正常'];
    }

    /**
     * 获取认证状态列表
     */
    public function getVerificationStatusList()
    {
        return [0 => '未认证', 1 => '已认证', 2 => '认证失败'];
    }

    /**
     * 关联商家审核表
     */
    public function audit()
    {
        return $this->hasOne('MerchantAudit', 'merchant_id', 'merchant_id');
    }
}
